package com.code.generator.cn.util;

import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


@Slf4j
public class ZipUtils {


    public static void createzip(List<File> fileList, String zipPath){
        FileInputStream nFileInputStream = null;
        ZipOutputStream nZipOutputStream = null;
        try {
            nZipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath));
            for (File file : fileList) {
                nFileInputStream = new FileInputStream(file);
                nZipOutputStream.putNextEntry(new ZipEntry(file.getName()));
                int len;
                while ((len = nFileInputStream.read()) != -1) {
                    nZipOutputStream.write(len);
                    nZipOutputStream.flush();
                }
            }
            nZipOutputStream.close();
            nFileInputStream.close();
            log.info("生成zip成功");
        } catch (Exception e1) {
            e1.printStackTrace();
            throw new  RuntimeException("生成zip失败");
        } finally {
            try {
                nFileInputStream.close();
                nZipOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("生成zip失败");
            }
        }
    }
}
